package start;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    private static final String HOST = "47.108.48.236";
    private static final int PORT = 5672;
    private static final String VIRTUAL_HOST = "test";
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置参数
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setVirtualHost(VIRTUAL_HOST);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        // 创建连接
        Connection connection = factory.newConnection();
        // 创建 channel
        Channel channel = connection.createChannel();
        /**
         * 声明队列
         * queue: 队列名称
         * durable：是否持久化，true：持久化队列存盘，服务器重启后消息不会丢失
         * exclusive：是否独占，仅限于此连接(Connection 关闭时，是否删除队列)
         * autoDelete: 是否自动删除, 当没有 Consumer 时，是否自动删除
         * arguments：相关参数
         */
        channel.queueDeclare("hello", true, false, false, null);

        // 消费当前队列
        /**
         * DefaultConsumer: RabbitMQ 提供的默认消费者，实现了 Consumer 接口
         * 核心方法: handleDelivery
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             *
             * @param consumerTag 消费者标签，通常是消费者在订阅队列时指定的
             * @param envelope 消息的封包信息(队列名称、交换机...)
             * @param properties 配置
             * @param body 消息内容
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
            }
        };
        /**
         * queue: 队列名称
         * autoAck: 是否自动确认，消费者收到消息后，自动与 MQ 进行确认
         * callback: 回调对象
         */
        channel.basicConsume("hello", true, consumer);
        // 等待回调函数执行完毕
        Thread.sleep(5000);
        // 释放资源
        channel.close();
        connection.close();
    }
}
